package com.yzg.simple.netty.http;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 *
 *  基于Netty 实现 http 服务器
 */
public class NettyHttpServer {

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
             bootstrap.group(bossGroup,worker)
                        .channel(NioServerSocketChannel.class)
                           .childHandler(new NettyHttpInitializer());

            ChannelFuture future = bootstrap.bind(8080).sync();
            //添加监听器等信息
            future.addListener(channelFut -> {
                if (future.isSuccess()) {
                    System.out.println("绑定端口成功 ~" + future.channel().localAddress());
                }else {
                    System.out.println("服务器启动失败 ~");
                }

            });
            //注意 Netty 是异步操作,所有执行的时候不会阻塞,启动成功后
            // 由bootstrap.bind(8080).sync(); 开子线程去执行流程,所以这里不会阻塞 先被释放,所有才能添加监听器.
             future.channel().closeFuture().sync();
        }finally {
          bossGroup.shutdownGracefully();
          worker.shutdownGracefully();
        }
    }
}
